package my.diplom.web.validators;

import org.springframework.validation.Validator;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.apache.log4j.Logger;
import my.diplom.entity.Project;
import my.diplom.entity.Order;

import java.util.Date;

/**
 * Created by IntelliJ IDEA.
 * User: GGobozov
 * Date: 11.08.2009
 * Time: 15:54:20
 * To change this template use File | Settings | File Templates.
 */
public class CreateOrderValidator implements Validator {

    private static final Logger log = Logger.getLogger(CreateOrderValidator.class);

    public boolean supports(Class clazz) {
        return Order.class.equals(clazz);
    }



    public void validate(Object o, Errors errors) {
        log.debug("validate order" + o);
        Order order = (Order) o;
        if (order == null) errors.reject("Null data received");

        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "cpu", "cpu.empty", "PCU is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "hdd", "hdd.empty", "HDD is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "ram", "ram.empty", "RAM is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "startDate", "startDate.empty", "startDate is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "finishDate", "finishDate.empty", "finishDate is required");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "project", "project.empty", "project is required");
        Date start = order.getStartDate();
        Date finish = order.getFinishDate();
        if (start != null && finish != null && start.after(finish)) {
            errors.rejectValue("startDate", "invalid.startDate", "startDate must be less than finishDate");
            errors.rejectValue("finishDate", "invalid.finishDate", "finishDate must be more than startDate!");
        }

    }

}
